package com.gai.shop.dao.impl;

import com.gai.shop.dao.AddressDao;
import com.gai.shop.entity.Address;
import com.gai.shop.entity.Page;
import com.gai.shop.util.DataBaseUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

public class AddressDaoImpl implements AddressDao {
    private final QueryRunner QR = new QueryRunner();

    /**
     *
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public List<Address> selectAddressByUid(Integer uid) throws Exception {
        //默认值没有排序再前 SELECT * FROM address WHERE uid = ?;
        return QR.query(DataBaseUtil.getConnection(),
                "SELECT * FROM address WHERE uid = ? ORDER BY astate DESC;",
                new BeanListHandler<>(Address.class),
                uid);
    }

    /**
     *
     * @param address
     * @return
     * @throws Exception
     */
    @Override
    public Integer InsertIntoAddress(Address address) throws Exception {
        return QR.update(DataBaseUtil.getConnection(),
                "INSERT INTO address VALUES (DEFAULT,?,?,?,?,?);",
                address.getUid(),
                address.getAname(),
                address.getAphone(),
                address.getAdetail(),
                address.getAstate());
    }

    /**
     * 删除
     * @param aid
     * @return
     * @throws Exception
     */
    @Override
    public Integer deleteAddressByAid(Integer aid) throws Exception {
        return QR.update(DataBaseUtil.getConnection(),
                "DELETE FROM address WHERE aid = ?;",
                aid);
    }

    /**
     * 修改
     * @param address
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateAddress(Address address) throws Exception {
        return QR.update(DataBaseUtil.getConnection(),
                "UPDATE address SET aname=?,aphone=?,adetail=? WHERE aid = ?;",
                address.getAname(),
                address.getAphone(),
                address.getAdetail(),
                address.getAid());
    }

    /**
     * 修改地址为默认
     * aid直接代表我们要设置为默认 地址的数据
     * @param aid
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateAddressByAidSetAstate(Integer aid) throws Exception {
        return QR.update(DataBaseUtil.getConnection(),
                "UPDATE address SET astate = 1 WHERE aid = ?;",
                aid);
    }

    /**
     * 修改其他地址为非默认
     *      aid直接代表我们要设置为默认地址的数据
     *      uid为了防止我们修改到其他用户的地址数据
     * @param aid
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Integer updateAddressByAidAndUidSetAstate(Integer aid, Integer uid) throws Exception {
        return QR.update(DataBaseUtil.getConnection(),
                "UPDATE address SET astate = 0 WHERE aid != ? AND uid = ?;",
                aid,
                uid);
    }
}
